package org.karelun.whiteboard.editparts;

import java.util.List;

import org.eclipse.draw2d.FreeformLayer;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.swt.widgets.Display;
import org.karelun.whiteboard.Sheet;
import org.karelun.whiteboard.WhiteboardPackage;
import org.karelun.whiteboard.gef.EditPart;
import org.karelun.whiteboard.gef.EditPolicy;
import org.karelun.whiteboard.gef.editparts.AbstractGraphicalEditPart;
import org.karelun.whiteboard.policy.SheetLayoutEditPolicy;

/**
 * @Author: KarelunHuang
 * @Date: Jan 23, 2013
 **/
public class SheetEditPart extends AbstractGraphicalEditPart implements Adapter{

	private Notifier notifier;
	
	@Override
	protected List<? extends Object> getModelChildren() {
		Sheet sheet = (Sheet)getModel();
		return sheet.getGraphs();
	}
	
	@Override
	protected IFigure createFigure() {
		FreeformLayer layer = new FreeformLayer();
		layer.setLayoutManager(new FreeformLayout());
		return layer;
	}

	@Override
	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new SheetLayoutEditPolicy());
	}
	
	@Override
	public void activate() {
		super.activate();
		((Sheet)getModel()).eAdapters().add(this);
	}
	
	@Override
	public void deactivate() {
		((Sheet)getModel()).eAdapters().remove(this);
		super.deactivate();
	}
	
	@Override
	public void notifyChanged(Notification notification) {
		int featureID = notification.getFeatureID(WhiteboardPackage.class);
		switch (featureID) {
		case WhiteboardPackage.SHEET__GRAPHS:
			Runnable runnable = new Runnable(){
				public void run() {
					refreshChildren();
				}
			};
			Display.getDefault().asyncExec(runnable);
			break;
		}
	}
	
	@Override
	protected void refreshVisuals() {
		if(children==null||children.isEmpty()){
			return;
		}
		for(Object child:children){
			((EditPart)child).refresh();
		}
	}

	@Override
	public Notifier getTarget() {
		return notifier;
	}

	@Override
	public void setTarget(Notifier newTarget) {
		this.notifier=newTarget;
	}

	@Override
	public boolean isAdapterForType(Object type) {
		return type.equals(getModel().getClass());
	}

}
